package cn.lp207663436.dynamicmanager.service.impl;

import cn.lp207663436.dynamicmanager.pojo.entity.CustomDataSourcePropertyEntity;
import cn.lp207663436.dynamicmanager.mapper.CustomDataSourcePropertyMapper;
import cn.lp207663436.dynamicmanager.service.CustomDataSourcePropertyService;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.Serializable;

/**
 * <p>
 * 自定义数据源表 服务实现类
 * </p>
 *
 * @author luopeng
 * @since 2023-07-04
 */
@Service
public class CustomDataSourcePropertyServiceImpl extends ServiceImpl<CustomDataSourcePropertyMapper, CustomDataSourcePropertyEntity> implements CustomDataSourcePropertyService {

    @Resource
    private DataSource dataSource;

    @Resource
    private DynamicDataSourceProperties dynamicDataSourceProperties;

    @Resource
    private DefaultDataSourceCreator dataSourceCreator;

    @Override
    public void addDatasource(DataSourceProperty dataSourceProperty) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(dataSourceProperty.getPoolName(), dataSource);
    }

    /**
     * 保存数据源对象到池中和数据库中
     * @param customDataSourcePropertyEntity 数据源实体对象
     * @return 是否成功保存
     */
    @Override
    public boolean save(CustomDataSourcePropertyEntity customDataSourcePropertyEntity) {
        boolean result = super.save(customDataSourcePropertyEntity);
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        BeanUtils.copyProperties(customDataSourcePropertyEntity, dataSourceProperty);
        addDatasource(dataSourceProperty);
        return result;
    }

    /**
     * 删除池中和数据库中的数据源
     * @param id 数据库id
     * @return 是否成功删除
     */
    @Override
    public boolean removeById(Serializable id) {
        CustomDataSourcePropertyEntity entity = this.getById(id);

        // 主数据源不可删除
        if (entity == null || dynamicDataSourceProperties.getPrimary().equalsIgnoreCase(entity.getPoolName())) {
            return false;
        }
        boolean result = super.removeById(id);
        removeDatasource(entity.getPoolName());
        return result;
    }

    @Override
    public void removeDatasource(String poolName) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(poolName);
    }
}
